package com.multi.thread.chapter06.demo04;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

public class Singleton implements Serializable {
	
	private Singleton() {};

	private static final long serialVersionUID = 1L;
	
	private static class SingletonHanler {
		private static final Singleton singleton = new Singleton();
	}
	
	public static Singleton getInstance() {
		return SingletonHanler.singleton;
	}
	
	protected Object readResolve() throws ObjectStreamException {
		System.out.println("调用了readResolve方法");
		return SingletonHanler.singleton;
	}
	
	public static void main(String[] args) throws Exception {
		Singleton singleton = Singleton.getInstance();
		FileOutputStream os = new FileOutputStream(new File("F:\\singletonFile.txt"));
		ObjectOutputStream oos = new ObjectOutputStream(os);
		oos.writeObject(singleton);
		oos.close();
		os.close();
		System.out.println(singleton.hashCode());
		
		FileInputStream in = new FileInputStream(new File("F:\\singletonFile.txt"));
		ObjectInputStream oin = new ObjectInputStream(in);
		Singleton single = (Singleton)oin.readObject();
		in.close();
		oin.close();
		System.out.println(single.hashCode());
	}

}
